package cn.zhx.xa.gateway.filter;


import cn.zhx.xa.model.constant.RedisKey;
import cn.zhx.xa.model.vo.common.Result;
import cn.zhx.xa.model.vo.common.ResultCodeEnum;
import cn.zhx.xa.utils.AuthContextUtil;
import cn.zhx.xa.utils.JwtUtils;
import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.Resource;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private JwtUtils jwtUtils;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求路径
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();

        //判断路径 /api/**/auth/**，登录校验
        if(antPathMatcher.match("/api/**/auth/**",path)) {
            //登录校验
            //从请求头获取token
            String token = "";
            List<String> tokenList = request.getHeaders().get("token");
            if(tokenList != null) {
                token = tokenList.get(0);
            }

            //如果token为空
            if(StringUtils.isEmpty(token)) {
                return out(response, ResultCodeEnum.LOGIN_AUTH);
            }
            // 如果token不为空，那么此时验证token的合法性
            //对token进行校验
            Long validUid = jwtUtils.getValidUid(token);
            if(ObjectUtils.isEmpty(validUid)) {
                return out(response,ResultCodeEnum.LOGIN_AUTH);
            }

            // 重置Redis中的token的有效时间
            stringRedisTemplate.expire(RedisKey.USER_LOGIN + validUid , RedisKey.TOKEN_EXPIRE_DAYS , TimeUnit.DAYS) ;
        }

        //放行
        return chain.filter(exchange);
    }


    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> out(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) {
        Result result = Result.build(null, resultCodeEnum);
        byte[] bits = JSONObject.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
